//
// Created by WenDaoJiang on 2017/6/21.
// Copyright (c) 2017 文道江. All rights reserved.
//

#import "ServerApi.h"

@implementation ServerApi {
    NSDictionary *loginInfo;
}

- (void)call:(NSString *)act params:(NSDictionary *)body completionHandler: (void(^)(NSDictionary *data, NSError *error))completionHandler{
    //TODO: ANDROID 服务端地址还需修改.

    NSDictionary *agora_signal_login_info = [KVStorage getJsonValue:@"agora_signal_login_info"];
    if (agora_signal_login_info != nil) {
        loginInfo = agora_signal_login_info;
    }

    // 读取配置信息
    NSDictionary *AgoraConfig = [[HybridBridge defaultHybridBridge] appInfo][@"Agora"];
    if (IS_DEBUG){
        NSDictionary *AgoraDebugConfig = [HybridBridge defaultHybridBridge].appInfo[@"AgoraDebug"];
        if (AgoraDebugConfig != nil)AgoraConfig = AgoraDebugConfig;
    }

    if(AgoraConfig == nil || AgoraConfig[@"RestfulServerHost"] == nil){
        NSLog(@"Agora RestfulServerHost Not Config.");
        return;
    }

    NSString *url = [NSString stringWithFormat:@"%@%@.json", AgoraConfig[@"RestfulServerHost"], act];

    NSString *auth = (loginInfo != nil && loginInfo[@"auth"] != nil) ? loginInfo[@"auth"] : @"";
    NSLog(@"@-------- %@, %@", auth, url);

    [[URLSessionManager ajaxPOST:url params:@{
            @"header": @{
                    @"auth": auth,
                    @"act": act,
                    @"source": @"MS",
                    @"ver": @(0)
            },
            @"body": body
    }          completionHandler:^(NSDictionary *data, NSError *error) {
        /*NSLog(@"data %@", data);
        if (error) {
            NSLog(@"error %@", error);
        }*/

        if (error != nil){
            completionHandler(data, error);
        }else {
            if(data[@"isSuccess"] != nil && [data[@"isSuccess"] boolValue]){
                completionHandler(data[@"body"], nil);
            }else{
                completionHandler(data, [NSError errorWithDomain:data[@"message"] code:2 userInfo:nil]);
            }
        }
    }] resume];
}

- (void)callProgresWithView:(UIView *)view act:(NSString *)act body:(NSDictionary *)body completionHandler: (void(^)(NSDictionary *data, NSError *error))completionHandler{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = @"请稍等";
    hud.mode = MBProgressHUDModeIndeterminate;
    [self call:act params:body completionHandler:^(NSDictionary *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hide:YES];
        });
        if(completionHandler != nil){
            completionHandler(data, error);
        }
    }];
}

@end